#include "board.h"
#include "components\battery_manager\battery_manager.h"
#include "polsys.h"

// 掉电保存数据存储位置，通常是一些设置参数
#define _ST_STORAGE_PADDR   0x11010000

// 默认
#define Board_VExtOn()             HalGpioSet(VEXT_EN_PIN, (bit_action_e)0)

#define Board_VExtOff()            HalGpioSet(VEXT_EN_PIN, (bit_action_e)1)

static vu16 mAdcKbValue = 0;
static vu16 mBatVoltage = 0;        // 电池电压 mV


const u8 Storage[4096] __attribute__((at(_ST_STORAGE_PADDR))) = {0};


void Board_Init()
{
    Gpio_Init();
    Board_VExtOn();
    Adc_Init();
    Adc_Enable(1 << ADC_CH_VBAT);
    Spi_Init();
    HalGpioFmuxConfig(SPI_MISO_PIN, FMUX_SPI_0_RX);
    HalGpioFmuxConfig(SPI_MOSI_PIN, FMUX_SPI_0_TX);
    HalGpioFmuxConfig(SPI_SCK_PIN, FMUX_SPI_0_SCK);

    // 刚上电时等待一次ADC采集结束
    Delay_ms(100);
    mBatVoltage = Adc_GetVoltage(ADC_CH_VBAT, 8) * 11;
    // if(mBatVoltage < 3350)  // 电量很低
    // {
    //     Board_EnterSleep();
    // }

    BM_Init();  // 确保之前电池电压可被正确获取

    Adc_Enable(1 << ADC_CH_KB);
}

u16 Board_GetKbValue()
{
    mAdcKbValue = Adc_GetVoltage(ADC_CH_KB, 8);
    return mAdcKbValue;
}

u16 Board_GetVBat()
{
    mBatVoltage = Adc_GetVoltage(ADC_CH_VBAT, 8) * 11;
    return mBatVoltage;
}

void Board_Sleep()
{
    // 模拟进入休眠，按钮按下唤醒
    while(mAdcKbValue < 100)
    {
        Board_GetKbValue();
    }
}



